//@include uploadDocument

GDataManager       = Packages.it.softphone.commons.gdata.GDataManager;
gdata              = Packages.com.google.gdata.data;
ApplicationConfig  = Packages.it.softphone.spring.ApplicationConfig;
SpreadsheetService = Packages.com.google.gdata.client.spreadsheet.SpreadsheetService;
CellEntry          = Packages.com.google.gdata.data.spreadsheet.CellEntry;
SpreadsheetEntry   = Packages.com.google.gdata.data.spreadsheet.SpreadsheetEntry;
TableEntry         = Packages.com.google.gdata.data.spreadsheet.TableEntry;
Data               = Packages.com.google.gdata.data.spreadsheet.Data;
FeedURLFactory     = Packages.com.google.gdata.client.spreadsheet.FeedURLFactory;
Worksheet          = Packages.com.google.gdata.data.spreadsheet.Worksheet;
SpreadsheetFeed    = Packages.com.google.gdata.data.spreadsheet.SpreadsheetFeed;
Data               = Packages.com.google.gdata.data.spreadsheet.Data;
PlainTextConstruct = Packages.com.google.gdata.data.PlainTextConstruct;
Header             = Packages.com.google.gdata.data.spreadsheet.Header;
Column             = Packages.com.google.gdata.data.spreadsheet.Column;
RecordEntry        = Packages.com.google.gdata.data.spreadsheet.RecordEntry;
Field              = Packages.com.google.gdata.data.spreadsheet.Field;


   function main( ui ) {
    try{
     var json = ui.getFirst("json");
   
     var username = "soulsoftware2010@gmail.com";
     var password = "2010soulsoftware";
       
     if ( json == null ){
        var ex = "{ exception: { message: 'no param provided'} }";
        return ex;
     }
     var o = new JSONObject( json );
     var array=o.get("events");
     var info=o.get("info");
      
     var employee=info.get("userId");
     var from=info.get("from");
     var to=info.get("to");  
      
     var fileName=employee +"_" + formatDate(from) + "_" + formatDate(to);
     
     var doc=gdataUploadDocument("/","Template-Badge.xls",
                "Reports",fileName,
                username,password,
               ["user:"+ employee]);
  
     
      createTable(doc.getId(),array,username,password);
      return "{result:'OK'}" ;
     }catch(e){
       return e;
     }
   }

   //TABLE SETTINGS...
   function setEntryContentsFromString( entryToUpdate,title,
                                        summary,worksheet,
                                        columns) {
      try{
        entryToUpdate.setTitle(new PlainTextConstruct(title));
        entryToUpdate.setSummary(new PlainTextConstruct(summary));                                  
        entryToUpdate.setWorksheet(new Worksheet(worksheet));  
        //NUM. LINE HEAD         
        entryToUpdate.setHeader(new Header(3));   
        
        var newData = new Data();      
        newData.setNumberOfRows(0); 
        //FIRST LINE   
        newData.setStartIndex(4);    
        newData.setInsertionMode(Data.InsertionMode.INSERT);   
         
        var cols = columns.split(";");
        var i = 0;                                  
        for (;i < cols.length; i++) {
              var colInfo = cols[i].split(":");
              var index = colInfo[0];
              var name = colInfo[1];
              newData.addColumn(new Column(index,name ));  
         }
                                
        entryToUpdate.setData(newData);
        
        return entryToUpdate;
       }catch(e){
         return e;
       }
     }

 
    
   // CREATE TABLE 
   function createTable(id,jasonArray,username,password ) {  
     try{
      var service = new SpreadsheetService("");
      
      service.setUserCredentials(username, password);
  
      var metafeedUrl = new java.net.URL("https://spreadsheets.google.com/feeds/spreadsheets/private/full");
  
      var feed = service.getFeed(metafeedUrl, SpreadsheetFeed);

      var spreadsheets = feed.getEntries();
      
      
      var entry=spreadsheets.get(0);
      var j=0;
      for (; j < spreadsheets.size(); j++) {
        var entryTest = spreadsheets.get(j);
        if (entryTest.getId().equals(id)){
          entry=entryTest;
          break;
        }
      }
      
      if (entry==null) throw new java.lang.Exception ("File Not Found ");
       
      var spreadsheetUrl = new java.net.URL(entry.getSpreadsheetLink().getHref());
      var baseUrl = new java.net.URL(spreadsheetUrl.getProtocol() + "://" + spreadsheetUrl.getHost()).toString();
      
      // TABLE CONFIG
      var headers = "a:EventCode;b:Company;c:Address;d:From;e:To;f:BadgeIn;g:BadgeOut;h:Valid";
  
      var tablesFeedUrl = new java.net.URL(baseUrl + "/feeds/" + entry.getKey()+ "/tables");
     
      var newEntry = setEntryContentsFromString(new TableEntry(),"EventsTable","EventsTable","Foglio1", headers);
      // CREATE TABLE
      service.insert(tablesFeedUrl, newEntry);
      
      var tableId = 0;
      var recordsFeedUrl =  new java.net.URL(baseUrl + "/feeds/" + entry.getKey() + "/records/" + tableId);
 
       // CREATE ROWS...
      var i=0;
      for (;i<jasonArray.length();i++){
         var o=jasonArray.getJSONObject(i);
         var newRecordEntry = new RecordEntry();
      
         newRecordEntry.addField(new Field(null, "EventCode", o.get("contractId")));
         newRecordEntry.addField(new Field(null, "Company", o.get("TITLE")));
         newRecordEntry.addField(new Field(null, "Address", o.get("ADDRESS")));
         newRecordEntry.addField(new Field(null, "From", formatDate (o.get("from"))));
         newRecordEntry.addField(new Field(null, "To", formatDate (o.get("to"))));
         newRecordEntry.addField(new Field(null, "BadgeIn", formatDate (o.get("badgeIn"))));
         newRecordEntry.addField(new Field(null, "BadgeOut", formatDate (o.get("badgeOut")))); 
         newRecordEntry.addField(new Field(null, "Valid", o.get("isValid")));
         //INSERT ROW
         service.insert(recordsFeedUrl, newRecordEntry);
      }
     }catch(e){ return e;}
   }

   function formatDate(value){
       try{
           if (value==0)return 0;
           var formatter = new java.text.SimpleDateFormat("yyyy-MM-dd");
           return formatter.format( value);
       }catch(e){
           return "";
       }
     }

  
  